/*****************************************************************************************
**  Author:COCO 2022
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
     //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      this.columnIndex = true; //显示序号(默认隐藏)
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });

      // 检验单明细表格配置
      this.detailColumns = [
        {field:'materialCode', title:'物品编号', width:120, align:'left', required:true},
        {field:'materialName', title:'物品名称', width:120, align:'left', required:true},
        {field:'modelNumber', title:'规格型号', width:100, align:'left'},
        {field:'unit', title:'单位', width:60, align:'left'},
        {field:'brand', title:'品牌', width:100, align:'left'},
        {field:'purchaseQuantity', title:'采购数量', width:100, align:'right', type:'number'},
        {field:'inspectionType', title:'检验类型', width:120, align:'center', 
          dropdown: {
            data:[
              {key:'免检', value:'免检'},
              {key:'抽检', value:'抽检'},
              {key:'全检', value:'全检'}
            ]
          }
        },
        {field:'receivedQuantity', title:'收货数量', width:120, align:'right', type:'number', required:true},
        {field:'defectQuantity', title:'不良数量', width:120, align:'right', type:'number'}
      ];
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      if (this.autoGenerateCode) {
        // 自动生成编号逻辑
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        formData.InspectionOrderCode = `JYDH${year}${month}${day}${random}`;
      }
      
      // 处理采购单信息
      if (this.purchaseInfo && this.purchaseInfo.purchaseOrderId) {
        formData.PurchaseOrderID = this.purchaseInfo.purchaseOrderId;
      }
      
      // 处理明细表数据
      if (this.detailData && this.detailData.length) {
        formData.InspectionDetails = this.detailData.map(item => {
          return {
            MaterialCode: item.materialCode,
            MaterialName: item.materialName,
            ModelNumber: item.modelNumber,
            Unit: item.unit,
            Brand: item.brand,
            PurchaseQuantity: item.purchaseQuantity,
            InspectionType: item.inspectionType,
            ReceivedQuantity: item.receivedQuantity,
            DefectQuantity: item.defectQuantity || 0
          };
        });
      }
      
      // 处理附件
      if (this.attachment) {
        formData.Attachments = [this.attachment];
      }
      
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      // 处理采购单信息
      if (this.purchaseInfo && this.purchaseInfo.purchaseOrderId) {
        formData.PurchaseOrderID = this.purchaseInfo.purchaseOrderId;
      }
      
      // 处理明细表数据
      if (this.detailData && this.detailData.length) {
        formData.InspectionDetails = this.detailData.map(item => {
          return {
            InspectionDetailId: item.inspectionDetailId || null, // 更新时需要ID
            MaterialCode: item.materialCode,
            MaterialName: item.materialName,
            ModelNumber: item.modelNumber,
            Unit: item.unit,
            Brand: item.brand,
            PurchaseQuantity: item.purchaseQuantity,
            InspectionType: item.inspectionType,
            ReceivedQuantity: item.receivedQuantity,
            DefectQuantity: item.defectQuantity || 0
          };
        });
      }
      
      // 处理附件
      if (this.attachment) {
        formData.Attachments = [this.attachment];
      }
      
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      if (!row) return; // 新建时不处理
      
      // 如果是编辑，需要加载采购单信息和明细数据
      if (row.PurchaseOrderID) {
        this.loadPurchaseInfo(row.PurchaseOrderID);
      }
      
      // 加载明细数据
      this.loadDetailData(row.InspectionOrderID);
      
      // 加载附件
      this.loadAttachments(row.InspectionOrderID);
    },
    // 下面是新增的自定义方法
    loadPurchaseInfo(purchaseOrderId) {
      // 从后端API获取采购单信息
      let url = `/api/Quality_InboundTest/GetTable1Data`;
      let http = require("@/api/http");
      
      // 确保purchaseOrderId是字符串
      const idParam = typeof purchaseOrderId === 'string' ? purchaseOrderId : purchaseOrderId.toString();
      
      http.post(url, {
        page: 1,
        rows: 30, // 获取更多记录以确保找到匹配的
        wheres: [
          { name: 'purchase_orderid', value: idParam, displayType: 'guid' }
        ]
      }, true).then(res => {
        // 检查返回的数据
        let orderData = null;
        
        if (res && res.rows && Array.isArray(res.rows)) {
          // 尝试找到匹配的订单
          orderData = res.rows.find(item => item.purchase_orderid === idParam);
          if (!orderData && res.rows.length > 0) {
            // 如果没找到精确匹配但有数据，使用第一条
            orderData = res.rows[0];
          }
        } else if (res && res.data && res.data.rows && Array.isArray(res.data.rows)) {
          // 尝试找到匹配的订单
          orderData = res.data.rows.find(item => item.purchase_orderid === idParam);
          if (!orderData && res.data.rows.length > 0) {
            // 如果没找到精确匹配但有数据，使用第一条
            orderData = res.data.rows[0];
          }
        }
        
        if (orderData) {
          // 将数据映射到purchaseInfo对象
          this.purchaseInfo = {
            purchaseOrderId: orderData.purchase_orderid,
            purchaseOrderCode: orderData.order_no,
            purchaseDate: orderData.purchase_date,
            supplierName: '未知供应商', // 后台未返回，可根据供应商ID查询
            contactPerson: '',
            supplierPhone: '',
            purchaser: '未知采购员',
            purchaseDepartment: '未知部门',
            purchaseContactPhone: '',
            related_project: orderData.related_project || ''
          };
          
          // 如果需要获取供应商信息，可以调用供应商API
          if (orderData.purchase_supplierid) {
            this.loadSupplierInfo(orderData.purchase_supplierid);
          }
          
          console.log('成功加载采购单信息:', this.purchaseInfo);
        } else {
          console.warn('没有找到采购单信息:', idParam);
          // 设置默认空值
          this.purchaseInfo = {
            purchaseOrderId: purchaseOrderId,
            purchaseOrderCode: '',
            purchaseDate: null,
            supplierName: '',
            contactPerson: '',
            supplierPhone: '',
            purchaser: '',
            purchaseDepartment: '',
            purchaseContactPhone: '',
            related_project: ''
          };
        }
      }).catch(err => {
        console.error('获取采购单信息失败:', err);
        // 设置默认空值
        this.purchaseInfo = {
          purchaseOrderId: purchaseOrderId,
          purchaseOrderCode: '',
          purchaseDate: null,
          supplierName: '',
          contactPerson: '',
          supplierPhone: '',
          purchaser: '',
          purchaseDepartment: '',
          purchaseContactPhone: '',
          related_project: ''
        };
      });
    },
    
    // 加载供应商信息（可选）
    loadSupplierInfo(supplierId) {
      // 这里可以调用获取供应商信息的API
      let http = require("@/api/http");
      
      // 如果有对应的API，可以取消注释以下代码
      /*
      http.get(`/api/Supplier/GetById?id=${supplierId}`, null, true).then(res => {
        if (res.status && res.data) {
          this.purchaseInfo.supplierName = res.data.supplier_name || '未知供应商';
          this.purchaseInfo.contactPerson = res.data.contact_person || '';
          this.purchaseInfo.supplierPhone = res.data.phone || '';
        }
      }).catch(err => {
        console.error('获取供应商信息失败:', err);
      });
      */
    },
    loadDetailData(inspectionOrderId) {
      // 这里应当从后端API获取检验明细数据
      console.log('加载检验明细数据', inspectionOrderId);
      // 模拟数据
      this.detailData = [
        {
          inspectionDetailId: '1',
          materialCode: 'WPBH7820864',
          materialName: '旺脑胶水250',
          modelNumber: 'WH-002',
          unit: '个',
          brand: '降龙十八掌',
          purchaseQuantity: 10,
          inspectionType: '免检',
          receivedQuantity: 10,
          defectQuantity: null
        },
        {
          inspectionDetailId: '2',
          materialCode: 'WPBH5786931',
          materialName: '旺脑胶水250',
          modelNumber: 'WH-002',
          unit: '个',
          brand: '降龙十八掌',
          purchaseQuantity: 10,
          inspectionType: '免检',
          receivedQuantity: 10,
          defectQuantity: null
        }
      ];
    },
    loadAttachments(inspectionOrderId) {
      // 这里应当从后端API获取附件信息
      console.log('加载附件信息', inspectionOrderId);
      // 模拟数据
      this.attachment = {
        name: '新建文本文档.PDF',
        size: '0',
        uploadDate: '2022-08-17 14:52:7'
      };
    },
    openPurchaseOrderDialog() {
      this.purchaseDialogVisible = true;
    },
    confirmSelectPurchase() {
      if (!this.selectedPurchase) {
        this.$message.warning('请选择一个采购单');
        return;
      }
      
      // 将选中的采购单信息填充到表单
      this.purchaseInfo = {
        purchaseOrderId: this.selectedPurchase.id,
        purchaseOrderCode: this.selectedPurchase.purchaseOrderCode,
        purchaseDate: this.selectedPurchase.purchaseDate,
        supplierName: this.selectedPurchase.supplierName,
        purchaser: this.selectedPurchase.purchaser,
        purchaseDepartment: this.selectedPurchase.purchaseDepartment,
        contactPerson: this.selectedPurchase.contactPerson || '',
        supplierPhone: this.selectedPurchase.supplierPhone || '',
        purchaseContactPhone: this.selectedPurchase.purchaseContactPhone || ''
      };
      
      // 将采购单ID保存到表单字段
      this.editFormFields.PurchaseOrderID = this.selectedPurchase.id;
      
      // 关闭弹窗
      this.purchaseDialogVisible = false;
      
      // 加载采购单对应的物料明细
      this.loadPurchaseDetails(this.selectedPurchase.id);
    },
    loadPurchaseDetails(purchaseOrderId) {
      // 这里应当从后端API获取采购单明细数据
      console.log('加载采购单明细数据', purchaseOrderId);
      // 模拟数据 - 实际应该根据采购单ID获取物料明细
      this.detailData = [
        {
          materialCode: 'WPBH7820864',
          materialName: '旺脑胶水250',
          modelNumber: 'WH-002',
          unit: '个',
          brand: '降龙十八掌',
          purchaseQuantity: 10,
          inspectionType: '免检',
          receivedQuantity: 10,
          defectQuantity: null
        },
        {
          materialCode: 'WPBH5786931',
          materialName: '旺脑胶水250',
          modelNumber: 'WH-002',
          unit: '个',
          brand: '降龙十八掌',
          purchaseQuantity: 10,
          inspectionType: '免检',
          receivedQuantity: 10,
          defectQuantity: null
        }
      ];
    },
    addDetail() {
      // 添加明细的逻辑
      this.$refs.detailForm.open();
    },
    editDetail(row) {
      // 编辑明细的逻辑
      this.$refs.detailForm.open(row);
    },
    fileChange(file) {
      console.log('文件变更', file);
      this.attachment = {
        name: file.name,
        size: file.size,
        uploadDate: new Date().toLocaleString(),
        file: file.raw
      };
    }
  }
};
export default extension;
